package tree;

import java.util.List;

public class TreeToDoublyList {

    private static TreeNode head,prev;


    private  static void  dfs(TreeNode node){
        if(node==null){
            return;
        }
        dfs(node.left);


        // if(node.left==null&&node.right==null){
        System.out.println(node.val);
        // }


        dfs(node.right);

    }


    public static TreeNode treeToDoublyList2(TreeNode node){
        if(node==null){
            return null;
        }
        dfs(node);
        // head.left = prev;
        // prev.right = head;
        return head;
    }

    public static TreeNode treeToDoublyList(TreeNode node) {

        if (node.left != null) {
            TreeNode result = treeToDoublyList(node.left);
            while(result.right!=null){
                result = result.right;
            }
            node.left = result;
            result.right = node;
        }

        if (node.right != null) {
            TreeNode result = treeToDoublyList(node.right);
            while(result.left!=null){
                result = result.left;
            }
            node.right = result;
            result.left = node;
        }

        return node;


    }


    public static void main(String[] args) {
        Integer[] nums = {4,2,5,1,3};
        // Integer[] nums2={1};
        TreeNode treeNode = TreeNode.constructTree(nums);
        TreeNode.printTree(treeNode);
        System.out.println(treeNode.getClass());


        dfs(treeNode);


    }

}
